package num24;

import java.util.List;

/**
 * @author : DuJiabao
 * @Project : sword-finger-offer
 * @Time : 2021/5/8 18:59
 * @Desc :
 */
public class Solution {
  public ListNode swapPairs(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p1 = head;
    ListNode p2 = head.next;
    ListNode p3 = null;
    head = p2;
    while (true) {
      p1.next = p2.next;
      p2.next = p1;
      if (p3 != null) p3.next = p2;
      if (p1.next == null || p1.next.next == null)
        break;
      p3 = p1;
      p1 = p1.next;
      p2 = p1.next;
    }
    return head;
  }

  public static void main(String[] args) {
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    ListNode node = new Solution().swapPairs(head);
    while (node != null) {
      System.out.println(node.val);
      node = node.next;
    }
  }

}

class ListNode {
  int val;
  ListNode next;

  ListNode() {
  }

  ListNode(int val) {
    this.val = val;
  }

  ListNode(int val, ListNode next) {
    this.val = val;
    this.next = next;
  }
}